//
//  DeliverThemeViewController.m
//  WDFans
//
//  Created by Zhihong Yuan on 2/15/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "DeliverThemeViewController.h"
#import "ActivityViewManager.h"
#import "ImageDetailViewController.h"

#import "ZHDataService.h"
#import "ZHWebService.h"
#import "JSON.h"


const CGFloat kTextViewHeight = 376.f;

@interface DeliverThemeViewController()

- (void)initUpperKeyboardView;
- (void)resignAllTextField;
@end

@implementation DeliverThemeViewController

@synthesize titleField,contentTextView,themeContentCotainView;
@synthesize upperView,titleLabel;
@synthesize getFile,fileData,fileName;
@synthesize upFile;
@synthesize viewType;
@synthesize titleName;
@synthesize tid,fid;





#pragma mark - my own methods
- (void)resignAllTextField
{
    [self.titleField resignFirstResponder];
    [self.contentTextView resignFirstResponder];
}

- (void)initUpperKeyboardView
{
    NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"UpperKeyboardView" owner:self options:nil];
    UpperKeyboardView *uv = (UpperKeyboardView *)[nibs lastObject];
    uv.delegate = self;
    self.upperView = uv;
}

- (void)keyBoardWillShow:(NSNotification *)notification
{
    NSDictionary *info = notification.userInfo;
    
    CGSize keybSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    
    CGRect rect = self.themeContentCotainView.frame;
    rect.size.height = kTextViewHeight-keybSize.height;
    self.themeContentCotainView.frame = rect;
}

- (void)keyBoardWillHide:(NSNotification *)notification
{
    CGRect rect = self.themeContentCotainView.frame;
    rect.size.height = kTextViewHeight;
    self.themeContentCotainView.frame = rect;
}

#pragma mark - AbstractTabViewController methods
- (IBAction)leftItemClicked
{
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)rightItemClicked
{
    if([self.titleField.text length]==0)
    {
        UIAlertView *alertView  = [[UIAlertView alloc] initWithTitle:@"提示" message:@"帖子标题不能为空" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
        [alertView release];
//        return;
//        [ActivityViewManager showErrorViewWithMessage:@"主题不能为空"];
    }
    else if([self.contentTextView.text length]<10)
    {
        UIAlertView *alertView  = [[UIAlertView alloc] initWithTitle:@"提示" message:@"帖子内容不能少于10个字节" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
        [alertView release];
//        [ActivityViewManager showErrorViewWithMessage:@"帖子内容不能为空"];
    }
    else
    {
        // 图片过大
        if([fileData length]>4409719)
        {
            UIAlertView *alertView  = [[UIAlertView alloc] initWithTitle:@"提示" message:@"图片过大" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alertView show];
            [alertView release];
            return;
        }
        
        if(upFile)
        {
            upFile.delegate =nil;
            [upFile release];
            upFile = nil;
        }
        
        [ActivityViewManager startedNetWorkActivityWithText:@"加载中..."];
        // 回帖
        if(self.viewType == kReplyType)
        {
            [self resignAllTextField];
            NSString* url = [NSString stringWithFormat:kUrlOfSendReply,fid,tid,[[ZHDataService sharedService] loginUser].authcode];
            
            // for test      
            //        NSString* url = [NSString stringWithFormat:kUrlOfSendReply,fid,tid,@"22a9Uc3h4Uq29l/aRHXevRrTL1kVkvBtgZSnygpdMUFtzTzhUqJKFmko2A2PS3SIgbYfNfDw8s7iEE4oO3k7C7u8zd1O_saltkey_77Z1c967"];
            
            
            upFile = [[UploadFile alloc] initWithDataForReply:url data:fileData imageName:fileName message:self.contentTextView.text];
            upFile.delegate = self;
            [upFile sendReply];
            
        }
        // 发帖
        else {
            
            if ([self.titleField.text length]<4||[self.titleField.text length]>80) {
                UIAlertView *alertView  = [[UIAlertView alloc] initWithTitle:@"提示" message:@"标题长度必须在4-80字节之间" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                [alertView show];
                [alertView release];
                return;
            }
            else if ([self.contentTextView.text length]<5) {
                UIAlertView *alertView  = [[UIAlertView alloc] initWithTitle:@"提示" message:@"正文内容至少需要5字节" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                [alertView show];
                [alertView release];
                return;
            }
            
            
            [self resignAllTextField];
            NSString* url = [NSString stringWithFormat:kUrlOfSendDeliver,fid,[[ZHDataService sharedService] loginUser].authcode];
            

            upFile = [[UploadFile alloc] initWithDataForDeliver:url data:fileData imageName:fileName subjectName:self.titleField.text message:self.contentTextView.text];
            upFile.delegate = self;
            [upFile sendDeliver];
        }
        
    }
    
    
    
    
    
    
}

#pragma mark - View lifecycle
- (id)initWithType:(ThemeViewType)type
{
    if(self = [super initWithNibName:@"DeliverThemeViewController" bundle:nil])
    {
        self.viewType = type;
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyBoardWillShow:) 
                                                     name:UIKeyboardWillShowNotification
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyBoardWillHide:) 
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];
    }
    return self;
}

- (void)dealloc
{
    [titleName release];
    
    if (upFile) {
        upFile.delegate = nil;
        [upFile release];
        upFile = nil;
    }
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [titleLabel release];
    [upFile release];
    [getFile release];
    [themeContentCotainView release];
    [upperView release];
    [contentTextView release];
    [titleField release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    UIImage *img = [UIImage imageWithData:self.fileData];
    [self.upperView.imgButton setImage:img forState:UIControlStateNormal];
    [self.upperView resetOffsetOfButtons];
    
    self.titleField.text = self.titleName;
    
    if ([self.titleField isFirstResponder]) {
        [self.titleField resignFirstResponder];
    }
    if(![self.contentTextView isFirstResponder])
        [self.contentTextView becomeFirstResponder];
    
    
    
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setBackgroundImageViewForPresentedView];
    [self initUpperKeyboardView];
    self.titleField.inputAccessoryView = self.upperView;
    self.contentTextView.inputAccessoryView = self.upperView;
//    [self.titleField becomeFirstResponder];
    if(self.viewType == kDeliverType)
    {
        self.titleLabel.text = @"发布帖子";
    }
    else if(self.viewType == kReplyType)
    {
        self.titleLabel.text = @"回复帖子";
        self.titleField.enabled = NO;
    }
    else
        self.titleLabel.text = @"新浪微博";
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.titleField = nil;
    self.contentTextView = nil;
    self.upperView = nil;
    self.themeContentCotainView = nil;
    self.titleLabel = nil;
}

#pragma mark - UpperKeyboardViewDelegate methods
- (void)didUpperKeyBoardButtonClick:(UIButton *)btn
{
    if(btn.tag == kHideKeyboardTab)
    {
//        [self resignAllTextField];
    }
    else if(btn.tag == kImageTab)
    {
        ImageDetailViewController *imgDetailController = [[ImageDetailViewController alloc] initWithImageData:self.fileData];
        [self presentModalViewController:imgDetailController animated:YES];
        [imgDetailController release];
    }
    else
    {
        GetPictureFromDevice *gf = [[GetPictureFromDevice alloc] initWithParentViewController:self];
        self.getFile = gf;
        [gf release];
        self.getFile.fileType = kPhotoType;
        self.getFile.delegate = self;
        if(btn.tag == kCameraTab)
        {
            [self.getFile takePhotoWithCamera];
        }
        else
            [self.getFile getPhotoFromLibrary];
    }
}
#pragma mark - UITextFieldDelegate methods
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.titleField resignFirstResponder];
    [self.contentTextView becomeFirstResponder];
    return NO;
}

#pragma mark - GetPictureFromDeviceDelegate methods
- (void)didGetFileWithData:(NSData *)data andName:(NSString *)name
{
    self.fileData = data;
    self.fileName = name;
}
- (void)didGetFileFailedWithMessage:(NSString *)mes
{
    [self resignAllTextField];
    [ActivityViewManager showErrorViewWithMessage:mes];
}

#pragma mark - UploadFileDelegate methods
- (void)uploadFile:(UploadFile *)controller didUploadFileSucceed:(NSString *)succeed
{
    [ActivityViewManager stoppedNetWorkActivity];
    [self dismissModalViewControllerAnimated:YES];
}

- (void)uploadFile:(UploadFile *)controller didUploadFileFailed:(NSString *)error
{
    [ActivityViewManager stoppedNetWorkActivity];
    UIAlertView *alertView  = [[UIAlertView alloc] initWithTitle:@"提示" message:error delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alertView show];
    [alertView release];
//    [ActivityViewManager showErrorViewWithMessage:error];
}
@end
